package com.yz.crm.weixin.action;


import com.yz.common.util.JDKStackTrace;
import com.yz.common.util.JsonUtils;
import com.yz.crm.weixin.bean.ValidResult;
import com.yz.crm.weixin.model.ThirdPartyUser;
import com.yz.crm.weixin.model.token.AuthUserInfoJson;
import com.yz.crm.weixin.service.ThirdPartyUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 数据保存服务
 * Created by DOVE on 2015/6/30.
 */
@Controller
@RequestMapping("/wechatcallback")
public class WechatCallback {
    private static final Log log = LogFactory.getLog(WechatCallback.class);
    @Resource
    private ThirdPartyUserService thirdPartyUserService;
/*
    @Resource
    private QRCodeService qrCodeService;*/

    /**
     * 用于 wechat 关注后保存用户信息
     *
     * @param request
     * @param session
     * @param response
     * @param map
     * @param userJson
     * @return
     */

    @RequestMapping("/saveWechatUserInfo")
    @ResponseBody
    public ValidResult saveWechatUserInfo(HttpServletRequest request,
                                          HttpSession session,
                                          HttpServletResponse response,
                                          ModelMap map,
                                          String userJson) {
        ValidResult validResult = new ValidResult();
        log.info("wechatcallback savewecharInfo userJson:" + userJson);
        if (StringUtils.isEmpty(userJson)) {
            log.info("wechatcallback savewecharInfo userJson为空");
            return validResult;
        }

        AuthUserInfoJson userInfoJson = null;
        try {
            userInfoJson = JsonUtils.toObject(userJson, AuthUserInfoJson.class);
        } catch (Exception e) {
            log.info("wechatcallback savewecharInfo userJson转化异常");
        }

        if (userInfoJson == null) {
            log.info("wechatcallback savewecharInfo userJson转化后为空");
            return validResult;
        }

        //数据库中添加用户信息（如果没有用户，重新添加，如果用户存在，更改状态）
        ThirdPartyUser thirdPartyUser = thirdPartyUserService.getInfo(null, userInfoJson.getOpenid());
        int result = 0;
        if (thirdPartyUser != null) {
            //第三方数据表存在该微信用户的信息，只需更新用户信息即可

            thirdPartyUser.setOpenId(userInfoJson.getOpenid());
            thirdPartyUser.setNickName(userInfoJson.getNickname());
            thirdPartyUser.setHeadImgUrl(userInfoJson.getHeadimgurl());
            thirdPartyUser.setSubscribed(true);
            thirdPartyUser.setUpdateDate(new Date());
            result = thirdPartyUserService.update(thirdPartyUser);
            if (result == 1) {
                validResult.setSuccess(true);
                log.info("wechatcallback savewecharInfo userJson:" + userJson + "update thirdPartyUser  success. toUserName=" + userInfoJson.getOpenid());
            } else {
                log.warn("wechatcallback savewecharInfo userJson:" + userJson + "update thirdPartyUser  error. toUserName=" + userInfoJson.getOpenid());
            }
        } else {
            try {
                thirdPartyUser = new ThirdPartyUser();
                thirdPartyUser.setOpenId(userInfoJson.getOpenid());
                thirdPartyUser.setNickName(userInfoJson.getNickname());
                thirdPartyUser.setHeadImgUrl(userInfoJson.getHeadimgurl());
                thirdPartyUser.setSubscribed(true);
                thirdPartyUser.setDelFlag(false);
                thirdPartyUser.setCreateDate(new Date());
                result = thirdPartyUserService.add(thirdPartyUser);
                if (result == 1) {
                    validResult.setSuccess(true);
                    log.info("wechatcallback savewecharInfo userJson:" + userJson + "add thirdPartyUser  success ");
                } else {
                    log.warn("wechatcallback savewecharInfo userJson:" + userJson + "add thirdPartyUser  error ");
                }
            } catch (Exception e) {
                log.warn("wechatcallback savewecharInfo userJson:" + userJson + "add thirdPartyUser  error " + JDKStackTrace.getJDKStrack(e));
            }

        }

        return validResult;
    }

    /**
     * 用于 wechat 取消关注后保存用户信息
     *
     * @param request
     * @param session
     * @param response
     * @param map
     * @param userJson
     * @return
     */

    @RequestMapping("/cancelSubscriber")
    @ResponseBody
    public ValidResult cancelSubscriber(HttpServletRequest request, HttpSession session, HttpServletResponse response, ModelMap map, String userJson) {
        ValidResult validResult = new ValidResult();
        log.info("wechatcallback cancelSubscriber userJson:" + userJson);
        if (StringUtils.isEmpty(userJson)) {
            log.info("wechatcallback cancelSubscriber userJson为空");
            validResult.setMsg("wechatcallback cancelSubscriber userJson为空");
            return validResult;
        }
        AuthUserInfoJson userInfoJson = null;
        try {
            userInfoJson = JsonUtils.toObject(userJson, AuthUserInfoJson.class);
        } catch (Exception e) {
            log.info("wechatcallback cancelSubscriber userJson转化异常");
        }

        if (userInfoJson == null) {
            log.info("wechatcallback cancelSubscriber userJson转化后为空");
            validResult.setMsg("wechatcallback cancelSubscriber userJson转化后为空");
            return validResult;
        }

        //更新数据库信息设置 isSubScribed 为false
        ThirdPartyUser baseThirdPartyUser = new ThirdPartyUser();
        baseThirdPartyUser.setSubscribed(false);
        baseThirdPartyUser.setOpenId(userInfoJson.getOpenid());
        try {
            int result = thirdPartyUserService.updateToUnBind(baseThirdPartyUser);
            if (result == 1) {
                validResult.setSuccess(true);
                log.info("Cancel attention   success ");
            } else {
                log.warn("Cancel attention   error ");
            }
        } catch (Exception e) {
            log.warn(JDKStackTrace.getJDKStrack(e));
        }

        return validResult;
    }


/**
 * 用于保存用户扫描二维码信息
 * 关注or scan
 *
 * @param request
 * @param session
 * @param response
 * @param map
 * @param wechatName
 * @param openId
 * @param ticket
 * @param accessType
 * @return
 */

   /* @RequestMapping("/saveQrcodeInfo")
    @ResponseBody
    public ValidResult saveQrcodeInfo(HttpServletRequest request,
                                     HttpSession session,
                                     HttpServletResponse response,
                                     ModelMap map,
                                     String wechatName,
                                     String openId,
                                     String ticket,
                                     Integer accessType) {
        ValidResult ValidResult = new ValidResult();
        log.info("微信访问二维码信息：wechatName：" + wechatName + ",openId:" + openId + ",ticket:" + ticket + ",accessType:" + accessType);
        try {
            ChannelQrcodeLog qrcodeLog = new ChannelQrcodeLog();
            if (StringUtils.isNotEmpty(ticket)) {
                BaseChannelInfo channelInfo = qrCodeService.queryChannelInfo(ticket);
                if (channelInfo != null) {
                    qrcodeLog.setChannelId(channelInfo.getId());
                    qrcodeLog.setCode(channelInfo.getCode());
                    qrcodeLog.setShortCode(channelInfo.getShortCode());
                    qrcodeLog.setTicket(channelInfo.getTicket());
                }
            }
            Date date = new Date();
            qrcodeLog.setCreateDate(date);
            qrcodeLog.setCreator("admin");
            qrcodeLog.setModifyDate(date);
            qrcodeLog.setModifier("admin");
            qrcodeLog.setTicket(ticket);
            qrcodeLog.setAccessType(accessType);
            qrcodeLog.setFromSite(wechatName);
            qrcodeLog.setOpenId(openId);
            //此时是否存在绑定关系的memberid，存在则保存此时的绑定快照
            ThirdParthUser baseThirdPartyUser = thirdPartyUserService.getInfo(null, openId, ThirdPartyUserType.WeixinSubType.PublicPlatform.ordinal());
            if (baseThirdPartyUser != null) {
                qrcodeLog.setMemberId(baseThirdPartyUser.getMemberId());
            }
            qrCodeService.saveQRCodeLogToMongo(qrcodeLog);
        } catch (Exception e) {
            log.info("存储二维码日志失败，" + JDKStackTrace.getJDKStrack(e));
        }
        return ValidResult;
    }*/



}
